package com.example.origin.demo.suanfa.leecode;


import java.util.HashSet;

/**
 * 给定一个字符串 s ，请你找出其中不含有重复字符的 最长
 * 子串
 *  的长度。
 *
 *
 *
 * 示例 1:
 *
 * 输入: s = "abcabcbb"
 * 输出: 3
 * 解释: 因为无重复字符的最长子串是 "abc"，所以其长度为 3。
 */
public class No03LengthOfLongestSubstring {
    public static void main(String[] args) {
        int i = lengthOfLongestSubstring2("abcabcbb");
        System.out.println(i);
    }


    /**
     * 滑动窗口
     * @param s
     * @return
     */
    public static int lengthOfLongestSubstring(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }

        HashSet<Character> set = new HashSet<>();
        int left = 0, right = 0;
        int maxLength = 0;

        while (right < s.length()) {
            // 添加新字符到set中，如果已经存在则表示有重复
            char c = s.charAt(right);
            if (!set.contains(c)) {
                set.add(c);
                maxLength = Math.max(maxLength, set.size());
                right++;
            } else {
                // 移除左边界字符，移动左边界
                set.remove(s.charAt(left));
                left++;
            }
        }

        return maxLength;
    }

    public static int lengthOfLongestSubstring2(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }

//        HashSet<Character> set = new HashSet<>();
//        int left = 0,right=0,maxLength =0;
//        while (right<s.length()){
//            char c = s.charAt(right);
//            if (set.contains(c)){
//                set.remove(s.charAt(left));
//                left++;
//            }else {
//                set.add(c);
//                maxLength = Math.max(maxLength,set.size());
//                right++;
//            }
//        }
//        return maxLength;

        HashSet<Character> set = new HashSet<>();
        int left = 0,right= 0,maxLength = 0;
        while (right<s.length()){
            char c = s.charAt(right);
            if (set.contains(c)) {
                set.remove(s.charAt(left));
                left++;
            }else {
                set.add(c);
                maxLength = Math.max(maxLength,set.size());
                right++;
            }
        }
        return maxLength;
    }

}
